﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
using System.Diagnostics;

namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }
        private const string namechcol = "Флаг";
        private SqlConnection conn;
        private delegate void Deleg();
        private Deleg del;
        private DateTime dNP1;
        private DateTime dOP1;
        private DateTime dNP2;
        private DateTime dOP2;
        private bool fl_but = false;
        private DataTable[] dt_res;
        private DataTable suppl = new DataTable();
        private DataTable dt_num;   //- для хранения выделенных поставщиков
        private DataTable dt_sup;   //- коды выбранных из фильтра поставщиков
        private int bId = 0;
        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            conn = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=AllPriceDW;Integrated Security=True");
            this.Text = "Сравнение периодов";
            this.dateNP1.Value = DateTime.Now.AddDays(-1).Date;
            this.dateOP1.Value = DateTime.Now.AddDays(-1).Date;
            this.dateNP2.Value = DateTime.Now.AddDays(-1).Date;
            this.dateOP2.Value = DateTime.Now.AddDays(-1).Date;
            dNP1 = dateNP1.Value;
            dOP1 = dateOP1.Value;
            dNP2 = dateNP2.Value;
            dOP2 = dateOP2.Value;
            SqlConnection conn_pholap = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=PharmOLAPDW;Integrated Security=True");
            listBox1.Items.Add("Все");
            suppl = (new SqlStorProc()).SqlProcExecWithQueryOneTable(conn_pholap, "pas_SupplSel", 600, null);
            foreach (DataColumn dc in suppl.Columns)
            {
                if (dc.ColumnName != "Флаг") dc.ReadOnly = true;
                else dc.ReadOnly = false;
            }
         }

        private void StartCreateRep(object sender, EventArgs e)
        {
            dataGridView2.DataSource = null;
            dataGridView1.DataSource = null;
            dt_num = new DataTable();
            fl_but = false;
            if (bId == 0)
                {
                    MessageBox.Show("Не выбрана база");
                    return;
                }
                del = new Deleg(CreateRep);
                this.Text += " Формируется";
                IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(CallBackFunc), null); 
                panel1.Enabled = false;
                dataGridView1.Enabled = false;
         }

        private void CallBackFunc(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            dataGridView1.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            dataGridView2.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            this.Invoke((Func<string>)(() => this.Text = this.Text.Replace(" Формируется", "")));
            if (dt_res.Length > 0)
            {
                fl_but = true;
                dataGridView2.Invoke((Func<object>)(() => dataGridView2.DataSource = dt_res[0].DefaultView));
                dataGridView2.Invoke((Func<object>)(() => dataGridView2.Columns[7].DefaultCellStyle.Format = "p"));
                dataGridView2.Invoke((Func<object>)(() => dataGridView2.Columns[9].DefaultCellStyle.Format = "p"));
            }
            
        }

        private void CallBackFuncNotAtt(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            dataGridView1.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            dataGridView2.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            this.Invoke((Func<string>)(() => this.Text = this.Text.Replace(" Формируется", "")));
            if (dt_res.Length > 0)
            {
                fl_but = true;
                dataGridView1.Invoke((Func<object>)(() => dataGridView1.DataSource = dt_res[0].DefaultView));
            }

        }

        private void CreateRep()
        {
            dt_res = new DataTable[2];
            dt_sup = new DataTable();
            dt_sup.Columns.Add();
            dt_num.Columns.Add();
   
            if (conn.State == ConnectionState.Closed) conn.Open();
            try
            {
                foreach (DataRow row in suppl.Rows)
                {
                    if (Convert.ToBoolean(row[namechcol]))
                    {
                        dt_sup.Rows.Add(row[1]);
                    }
                }
                if (dt_sup.Rows.Count == 0)
                {
                    foreach (DataRow row in suppl.Rows)
                    {
                        dt_sup.Rows.Add(row[1]);
                    }

                }
                SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[6];
                par[0].name = "@baseid";
                par[0].value = bId;
                par[1].name = "@dateNP1";
                par[1].value = dNP1;
                par[2].name = "@dateOP1";
                par[2].value = dOP1;
                par[3].name = "@dateNP2";
                par[3].value = dNP2;
                par[4].name = "@dateOP2";
                par[4].value = dOP2;
                par[5].name = "@tabl";
                par[5].value = dt_sup;
                dt_res = (new SqlStorProc()).SqlProcExecWithQuery(conn, "ComplarePeriods", 1500, par);
               // dt_sup = null;
                
                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                conn.Close();
            }

        }

        private void CreateNotAttachedRep()
        {
            //- Создание отчёта непривязанных позиций
            if (conn.State == ConnectionState.Closed) conn.Open();
            try
            {
                SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[6];
                par[0].name = "@baseid";
                par[0].value = bId;
                par[1].name = "@dateNP1";
                par[1].value = dNP1;
                par[2].name = "@dateOP1";
                par[2].value = dOP1;
                par[3].name = "@dateNP2";
                par[3].value = dNP2;
                par[4].name = "@dateOP2";
                par[4].value = dOP2;
                par[5].name = "@tabl";
                if (dt_num.Rows.Count > 0)
                {
                    par[5].value = dt_num;
                }
                else
                {
                    par[5].value = dt_sup;
                }
                dt_res = (new SqlStorProc()).SqlProcExecWithQuery(conn, "NotAttach", 300, par);
                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                conn.Close();
            }
        }

        /* Экспорт в Excel*/
        private void ExpToExcel(object sender, EventArgs e)
        {
            if (sender == this.btnExport)
            {
                SaveFileDialog sfd1 = new SaveFileDialog();
                sfd1.FileName = "Сравнение периодов";
                sfd1.Filter = "Файл CSV | *.csv";
                if (sfd1.ShowDialog() == DialogResult.OK)
                {
                    SaveDGVToCSVfile(sfd1.FileName.ToString(), dataGridView2, true);
                }
            }
            else if (sender == this.button3)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.FileName = "Непривязанные позиции";
                sfd.Filter = "Файл CSV | *.csv";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    SaveDGVToCSVfile(sfd.FileName.ToString(), dataGridView1, true);
                }
            }
        }
        /* Сохранение в формат csv*/
        public static bool SaveDGVToCSVfile(string filename, DataGridView table, bool openInExcel)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filename, false, Encoding.Unicode);

                List<int> col_n = new List<int>();
                foreach (DataGridViewColumn col in table.Columns)
                    if (col.Visible)
                    {
                        sw.Write(col.HeaderText + "\t");
                        col_n.Add(col.Index);
                    }
                sw.WriteLine();
                int x = table.RowCount;
                if (table.AllowUserToAddRows) x--;

                for (int i = 0; i < x; i++)
                {
                    for (int y = 0; y < col_n.Count; y++)
                        sw.Write(table[col_n[y], i].Value + "\t");
                    sw.Write(" \r\n");
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }

            if (openInExcel)
            {
                try
                {
                    Process newProc = Process.Start("excel.exe", "\"" + filename + "\"");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
            return true;
        }

        private void dateNP1_ValueChanged(object sender, EventArgs e)
        {
            dNP1 = dateNP1.Value;
        }

        private void dateOP1_ValueChanged(object sender, EventArgs e)
        {
            dOP1 = dateOP1.Value;
        }

        private void dateNP2_ValueChanged(object sender, EventArgs e)
        {
            dNP2 = dateNP2.Value;
        }

        private void dateOP2_ValueChanged(object sender, EventArgs e)
        {
            dOP2 = dateOP2.Value;
        }

        private void cmbBase_SelectedIndexChanged(object sender, EventArgs e)
        {
            bId = this.cmbBase.SelectedIndex + 1;
        }
        /* Вызов фильтра по поставщикам */
        private void button1_Click(object sender, EventArgs e)
        {
            int fl = 0;
            listBox1.Items.Clear();
            suppl = FiltFormShow("Поставщики", namechcol, "Поставщик", suppl);
            fl = 0;
            foreach (DataRow dr in suppl.Rows)
            {
                if (Convert.ToBoolean(dr["Флаг"]))
                {
                    fl++;
                    listBox1.Items.Add(dr["Поставщик"].ToString());
                }
            }
            if (fl == 0)
            {
                listBox1.Items.Add("Все");

            }
        }
        /* Фильтр по поставщикам */
        public DataTable FiltFormShow(string formname, string flname, string sort, DataTable dt)
        {
            PharmFilter.PharmFilter f = new PharmFilter.PharmFilter();
            f.Name = formname;
            f.dataGridView1.DataSource = dt.DefaultView;
            f.namechcol = flname;
            f.sortcoumn = sort;
            f.ShowDialog();
            f.Close();
            f = null;
            return dt;
        }
        /* Создание отчёта по непривязанным позициям */
        private void button2_Click(object sender, EventArgs e)
        {
            if (fl_but == false)
            {
                MessageBox.Show("Не сформирован отчёт по сравнению периодов");
                return;
            }
            del = new Deleg(CreateNotAttachedRep);
            this.Text += " Формируется";
            IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(CallBackFuncNotAtt), null);
            panel1.Enabled = false;
            dataGridView1.Enabled = false;


         }

        private void dataGridView2_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            /* Выделение строки при нажатии insert*/
            int i;
            if (e.KeyCode == Keys.Insert)
            {
                if (dataGridView2.CurrentRow.DefaultCellStyle.BackColor == Color.Empty)
                {
                    dataGridView2.CurrentRow.DefaultCellStyle.BackColor = Color.LightGreen;
                    dt_num.Rows.Add(dataGridView2.CurrentRow.Cells[0].Value);
                }
                else
                {
                    dataGridView2.CurrentRow.DefaultCellStyle.BackColor = Color.Empty;
                    for (i = 0; i < dt_num.Rows.Count; i++)
                    {
                        if (Convert.ToInt32(dt_num.Rows[i][0]) == Convert.ToInt32(dataGridView2.CurrentRow.Cells[0].Value))
                        {
                            dt_num.Rows[i].Delete();
                        }
                    }
                    dt_num.AcceptChanges();
                }
            }
        }

    }
}
